import { getUserProfileAPI } from '@/api/user'
import { getEmpInfoAPI } from '@/api/emp'
import dynamicRoutes from '@/router/dynamicRoutes.js'
import router, { constantRoutes, resetRouter } from '@/router'
export default {
  namespaced: true,
  state() {
    return {
      token: '',
      info: {},
      routes: []
    }
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
    },
    // 把合并后的用户的信息，保存到 state 中
    updateInfo(state, info) {
      state.info = info
    },
    updateRoutes(state, menus) {
      const arr = []
      for (const k in dynamicRoutes) {
        if (menus.includes(k)) {
          arr.push(dynamicRoutes[k])
        }
      }
      arr.push({ path: '*', redirect: '/404', hidden: true })
      // console.log(menus)
      // console.log(dynamicRoutes)
      // state.routes = arr
      state.routes = [...constantRoutes, ...arr]
      resetRouter()
      router.addRoutes(arr)
    },
    cleanRoutes(state) {
      state.routes = []
    }
  },
  actions: {
    // 获取用户信息
    async initUserInfo(ctx) {
      const profile = await getUserProfileAPI()
      // console.log(profile)
      // 获取员工的基本信息
      const emp = await getEmpInfoAPI(profile.data.userId)
      // console.log(emp)
      const userinfo = { ...profile.data, ...emp.data }
      // console.log(userinfo)
      ctx.commit('updateInfo', userinfo)
      ctx.commit('updateRoutes', userinfo.roles.menus)
    }
  }
}
